using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace HyuFrameWork
{
    public abstract class AudioHub : MonoBehaviour
    {
        public List<AudioController> audios = new List<AudioController>();
        private ResService _resService;
        public ResService ResService => _resService ??= ServiceManager.Check<ResService>();
        protected virtual void Start() => OnInit();

        public Action<AudioController> onCtrlInit;
        protected virtual void OnInit() 
        {
            audios.Clear();
            
            var srcs = transform.GetComponentsInChildren<AudioController>(true);
            audios.AddRange(srcs);
            foreach (var ctrl in audios) 
            {
                ctrl.Init(this);
                onCtrlInit(ctrl);
            }
            if (audios.Count <= 0) 
            {
                SpawnNew("Main");
            }
        }
        
        protected virtual AudioController SpawnNew(string newName = "") 
        {
            return null;
        }

        public AudioController GetIdle() 
        {
            var first = audios.FirstOrDefault(c => ! c.IsPlaying);
            if (first == null) 
                first = SpawnNew();
            return first;
        }

        public AudioController GetFirst() => audios[0];
        
        public void SetVolumnRate(float v) 
        {
            ForEach((c) => { c.Volumn = v; });
        }
        
        public void SetMute(bool mute) => ForEach(a => a.Mute = mute);

        public void Pause(bool bPause) => ForEach((c) => c.Pause(bPause));
            
        public void Stop() => ForEach((c) => { c.Stop(); });
        
        private void ForEach(Action<AudioController> a) 
        {
            foreach (var src in audios) 
            {
                a(src);
            }
        }
    }
}